// 名称正则校验
const pattern: any = [
  /^(\d{4})年(\d{1,2})月(\d{1,2})日$/,
  /^.*kV.*线$/,
  /^.*kV.*线.*支线$/,
  /^(#.*|.*#)$/
]
// const data = [
//   '2023年05月09日',
//   '10kV教育园116线',
//   '10kV教育园116线支线',
//   '001#'
// ]
// data.every((item, index) => pattern[index]?.test(item))

// eslint-disable-next-line @typescript-eslint/promise-function-async
export const verifyPackage = (folderPaths: string[]) => {
  return new Promise((resolve, reject) => {
    let maxFilePath: any = []
    const lineFolder: any = [] // 线路文件夹
    const folderNameMap = new Map() // 文件夹 Map 数据

    try {
      folderPaths.forEach((relativePath) => {
        const processedName = relativePath.replace(/\s/g, '').toLowerCase() // 去空&全小写的文件名去校验是否重名
        // 获取最长的路径传给后端
        const tPath: string[] = relativePath.split('/')
        const matches = relativePath.match(/^[^/]+\/[^/]+\//) // 获取线路文件夹路径，匹配第二个 / 之前的内容
        const result = matches !== null ? matches[0] : ''
        if (result.length !== 0 && lineFolder.includes(result) === false) {
          lineFolder.push(result)
        }
        maxFilePath = tPath.length > maxFilePath.length ? tPath : maxFilePath
        // 文件夹命名校验
        const nameFlag = tPath.every((item: string, index) => {
          if (pattern[index] !== undefined && Boolean(item?.length)) {
            if (index === 2 && !item.includes('支线')) {
              return pattern[3].test(item)
            }
            return pattern[index].test(item)
          }
          return true
        })
        // 文件夹重名校验
        let duplicateFlag = false
        if (folderNameMap.has(processedName)) {
          duplicateFlag = true
        } else {
          folderNameMap.set(processedName, {
            isEmpty: true
          })
        }
        // 校验命名规则错误
        if (!nameFlag || duplicateFlag) {
          throw new Error('命名规则错误')
        }
      })
      resolve({
        maxFilePath: maxFilePath?.join('/'),
        lineFolder
      })
    } catch (err) {
      reject(err)
    }
  })
}

// 处理提取到的文件：rar/7z
export function extractFilePaths(obj: any, currentPath = '') {
  const paths = []
  for (const key in obj) {
    if (obj[key] instanceof File) {
      paths.push(currentPath)
    } else if (typeof obj[key] === 'object') {
      const tPath: any = currentPath + key + '/'
      if (Object.keys(obj[key]).length !== 0) {
        const nestedPaths: any = extractFilePaths(obj[key], tPath)
        paths.push(...nestedPaths)
      } else {
        paths.push(tPath)
      }
    }
  }
  return paths
}

// 判断是否大于1G
export function isFileSizeGreaterThan1GB(file: File) {
  const fileSizeInBytes = file.size
  const fileSizeInGB = fileSizeInBytes / (1024 * 1024 * 1024) // 转换为GB
  return fileSizeInGB > 1
}
